package view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import utils.ValidateFormTools;
import model.bean.Department;
import model.dao.DepartmentDAO;

public class PnlAdminDepartmentManage extends JPanel{

		private JButton 	btnAddNew;
	    private JButton 	btnDelete;
	    private JButton 	btnUpdate;
	    private JLabel 		jLabel3;
	    private JLabel 		jLabel4;
	    private JLabel 		jLabel5;
	    private JLabel 		jLabel6;
	    private JPanel 		pnlAddDepartment;
	    private JPanel 		pnlBottom;
	    private JPanel 		pnlEditDepartment;
	    private JPanel 		pnlTop;
	    private JScrollPane spnlDepartmentData;
	    private JTable 		tblData;
	    private JTextField 	tfAddDepartmentID;
	    private JTextField 	tfAddDepartmentName;
	    private JTextField 	tfEditDepartmentID;
	    private JTextField 	tfEditDepartmentName;
	    
	    DefaultTableModel tblModel = new DefaultTableModel();

	    /** create form ManageDepartment */
	    public PnlAdminDepartmentManage() {
	        initComponents();

	        loadTableData();

	       

	    }

	    private void initComponents() {

	        pnlTop 				 = new JPanel();
	        pnlEditDepartment 	 = new JPanel();
	        btnUpdate 			 = new JButton();
	        tfEditDepartmentID 	 = new JTextField();
	        jLabel4 			 = new JLabel();
	        tfEditDepartmentName = new JTextField();
	        jLabel3 			 = new JLabel();
	        btnDelete  			 = new JButton();
	        pnlAddDepartment 	 = new JPanel();
	        btnAddNew 			 = new JButton();
	        tfAddDepartmentID 	 = new JTextField();
	        tfAddDepartmentName  = new JTextField();
	        jLabel6 			 = new JLabel();
	        jLabel5 			 = new JLabel();
	        pnlBottom 			 = new JPanel();
	        spnlDepartmentData 	 = new JScrollPane();
	        tblData 			 = new JTable();

	        setPreferredSize(new Dimension(791, 655));
	        setLayout(new BorderLayout());

	        pnlTop.setLayout(new BorderLayout());

	        pnlEditDepartment.setBorder(BorderFactory.createTitledBorder(null, "edit", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Calibri", 1, 12))); 
	        pnlEditDepartment.setPreferredSize(new Dimension(707, 80));

	        btnUpdate.setIcon(new ImageIcon(getClass().getResource("/images/btn_save.png"))); 
	        btnUpdate.setText("save");
	        btnUpdate.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent evt) {
	                btnUpdateActionPerformed(evt);
	            }
	        });

	        tfEditDepartmentID.setEditable(false);
	        tfEditDepartmentID.setEnabled(false);

	        jLabel4.setText("Department id");

	        jLabel3.setText("Department name");

	        btnDelete.setIcon(new ImageIcon(getClass().getResource("/images/btn_delete.png"))); 
	        btnDelete.setText("delete");
	        btnDelete.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent evt) {
	                btnDeleteActionPerformed(evt);
	            }
	        });

	        GroupLayout pnlEditDepartmentLayout = new GroupLayout(pnlEditDepartment);
	        pnlEditDepartment.setLayout(pnlEditDepartmentLayout);
	        pnlEditDepartmentLayout.setHorizontalGroup(
	            pnlEditDepartmentLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(pnlEditDepartmentLayout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(jLabel4)
	                .addPreferredGap(ComponentPlacement.RELATED)
	                .addComponent(tfEditDepartmentID, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
	                .addGap(18, 18, 18)
	                .addComponent(jLabel3)
	                .addGap(4, 4, 4)
	                .addComponent(tfEditDepartmentName, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE)
	                .addGap(18, 18, 18)
	                .addComponent(btnUpdate, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(ComponentPlacement.UNRELATED)
	                .addComponent(btnDelete)
	                .addContainerGap(36, Short.MAX_VALUE))
	        );

	        pnlEditDepartmentLayout.linkSize(SwingConstants.HORIZONTAL, new Component[] {btnDelete, btnUpdate});

	        pnlEditDepartmentLayout.setVerticalGroup(
	            pnlEditDepartmentLayout.createParallelGroup(Alignment.LEADING)
	            .addGroup(pnlEditDepartmentLayout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(pnlEditDepartmentLayout.createParallelGroup(Alignment.BASELINE)
	                    .addComponent(jLabel4)
	                    .addComponent(tfEditDepartmentID, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(jLabel3)
	                    .addComponent(tfEditDepartmentName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(btnUpdate)
	                    .addComponent(btnDelete))
	                .addContainerGap(18, Short.MAX_VALUE))
	        );

	        pnlTop.add(pnlEditDepartment, BorderLayout.CENTER);

	        pnlAddDepartment.setBorder(BorderFactory.createTitledBorder(null, "create", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Calibri", 1, 12))); 
	        pnlAddDepartment.setPreferredSize(new Dimension(707, 80));

	        btnAddNew.setIcon(new ImageIcon(getClass().getResource("/images/btn_add.png"))); 
	        btnAddNew.setText("create new");
	        btnAddNew.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent evt) {
	                btnAddNewActionPerformed(evt);
	            }
	        });

	        tfAddDepartmentID.setEditable(false);
	        tfAddDepartmentID.setEnabled(false);

	        jLabel6.setText("Department id");

	        jLabel5.setText("Department name");

	        javax.swing.GroupLayout pnlAddDepartmentLayout = new GroupLayout(pnlAddDepartment);
	        pnlAddDepartment.setLayout(pnlAddDepartmentLayout);
	        pnlAddDepartmentLayout.setHorizontalGroup(
	            pnlAddDepartmentLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(pnlAddDepartmentLayout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(jLabel6)
	                .addPreferredGap(ComponentPlacement.RELATED)
	                .addComponent(tfAddDepartmentID, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
	                .addGap(18, 18, 18)
	                .addComponent(jLabel5)
	                .addGap(4, 4, 4)
	                .addComponent(tfAddDepartmentName, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE)
	                .addGap(18, 18, 18)
	                .addComponent(btnAddNew, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
	                .addContainerGap(146, Short.MAX_VALUE))
	        );
	        pnlAddDepartmentLayout.setVerticalGroup(
	            pnlAddDepartmentLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(pnlAddDepartmentLayout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(pnlAddDepartmentLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
	                    .addComponent(btnAddNew)
	                    .addComponent(jLabel6)
	                    .addComponent(tfAddDepartmentID, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(jLabel5)
	                    .addComponent(tfAddDepartmentName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
	                .addContainerGap(18, Short.MAX_VALUE))
	        );

	        pnlTop.add(pnlAddDepartment, BorderLayout.PAGE_START);

	        add(pnlTop, BorderLayout.PAGE_START);

	        pnlBottom.setBorder(BorderFactory.createTitledBorder(null, "DepartmentList", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Calibri", 1, 12))); 
	        pnlBottom.setLayout(new BorderLayout());

	        spnlDepartmentData.setBorder(null);

	        tblData.setModel(new DefaultTableModel(
	            new Object [][] {
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null}
	            },
	            new String [] {
	                "Title 1", "Title 2", "Title 3", "Title 4"
	            }
	        ));
	        tblData.setFont(new Font("Verdana", 1, 12));
	        tblData.addMouseListener(new MouseAdapter() {
	            public void mouseClicked(MouseEvent evt) {
	                tblDataMouseClicked(evt);
	            }
	        });
	        tblData.addInputMethodListener(new InputMethodListener() {
	            public void caretPositionChanged(InputMethodEvent evt) {
	                tblDataCaretPositionChanged(evt);
	            }
	            public void inputMethodTextChanged(InputMethodEvent evt) {
	            }
	        });
	        tblData.addKeyListener(new KeyAdapter() {
	            public void keyPressed(KeyEvent evt) {
	                tblDataKeyPressed(evt);
	            }
	            public void keyReleased(KeyEvent evt) {
	                tblDataKeyReleased(evt);
	            }
	            public void keyTyped(KeyEvent evt) {
	                tblDataKeyTyped(evt);
	            }
	        });
	        spnlDepartmentData.setViewportView(tblData);

	        pnlBottom.add(spnlDepartmentData, BorderLayout.CENTER);

	        add(pnlBottom, BorderLayout.CENTER);
	    }

	    private void btnAddNewActionPerformed(ActionEvent evt) {
	        if (validateAddNew()) {
	            Department deptObj = new Department();
	            deptObj.setDepartmentId(0);
	            deptObj.setDepartmentName(tfAddDepartmentName.getText());

	            //try {
	                DepartmentDAO.insertDepartment(deptObj);
	                JOptionPane.showMessageDialog(null, "Insert new department success");
	                loadTableData();
	                tfAddDepartmentName.setText("");
//	            } catch (SQLException ex) {
//	                JOptionPane.showMessageDialog(null, " !", "", JOptionPane.ERROR_MESSAGE);
//	                ex.printStackTrace();
//	            } catch (ClassNotFoundException ex) {
//	                JOptionPane.showMessageDialog(null, " !", "", JOptionPane.ERROR_MESSAGE);
//	                ex.printStackTrace();
//	            }
	        }
	        
	}

	    private void tblDataMouseClicked(MouseEvent evt) {
	        getEditData();
	    }

	    private void btnUpdateActionPerformed(ActionEvent evt) {
	        if (tfEditDepartmentID.getText().compareTo("") != 0) {
	            if (validateEdit()) {
	                Department deptObj = new Department();
	                deptObj.setDepartmentId(Integer.parseInt(tfEditDepartmentID.getText()));
	                deptObj.setDepartmentName(tfEditDepartmentName.getText());

	               // try {
	                    DepartmentDAO.updateDepartment(deptObj);
	                    JOptionPane.showMessageDialog(null, "update department success.");
	                    loadTableData();
//	                } catch (SQLException ex) {
//	                    JOptionPane.showMessageDialog(null, " ", "", JOptionPane.ERROR_MESSAGE);
//	                    ex.printStackTrace();
//	                } catch (ClassNotFoundException ex) {
//	                    JOptionPane.showMessageDialog(null, " ", "", JOptionPane.ERROR_MESSAGE);
//	                    ex.printStackTrace();
//	                }
	            }
	        }
	        else {
	            JOptionPane.showMessageDialog(null, "You must select one row at under!!!",
	                    "not row selected", JOptionPane.INFORMATION_MESSAGE);
	        }
	    }

	    private void btnDeleteActionPerformed(ActionEvent evt) {
	        if (tblData.getSelectedRowCount() != 0) {
	            if (validateDelete()) {
	                if (JOptionPane.showConfirmDialog(null,
	                        " You want to delete this department?",
	                        "Delete",
	                        JOptionPane.OK_CANCEL_OPTION)
	                        == JOptionPane.OK_OPTION) {
	                   // try {

	                        DepartmentDAO.deleteDepartment(Integer.parseInt(tfEditDepartmentID.getText()));
	                        JOptionPane.showMessageDialog(null, "delete success");
	                        loadTableData();
	                        tfEditDepartmentID.setText("");
	                        tfEditDepartmentName.setText("");

//	                    } catch (SQLException ex) {
//	                        JOptionPane.showMessageDialog(null, "", "", JOptionPane.ERROR_MESSAGE);
//	                        ex.printStackTrace();
//	                    } catch (ClassNotFoundException ex) {
//	                        JOptionPane.showMessageDialog(null, "", "", JOptionPane.ERROR_MESSAGE);
//	                        ex.printStackTrace();
//	                    }

	                }
	            }
	        }
	    }

	    private void tblDataCaretPositionChanged(InputMethodEvent evt) {
	    }

	    private void tblDataKeyPressed(KeyEvent evt) {
	    }

	    private void tblDataKeyTyped(KeyEvent evt) {
	    }

	    private void tblDataKeyReleased(KeyEvent evt) {
	        getEditData();
	    }

	    
	    private boolean validateAddNew() {
	        String msg = "";
	        
	        if (!ValidateFormTools.isFilledTextField(tfAddDepartmentName, true))
	        {
	            msg += "\n- Department name must not null.";
	        }
	        tfAddDepartmentName.setText(tfAddDepartmentName.getText().trim());


	        if (msg.compareTo("") != 0) {
	            JOptionPane.showMessageDialog(null,
	                    "Have some error" + msg,
	                    "new error",
	                    JOptionPane.ERROR_MESSAGE);
	            return false;
	        } else {
	            return true;
	        }
	    }

	    private boolean validateDelete() {
	        int rowIndex = tblData.getSelectedRow();
	        int EmpNo = Integer.parseInt(tblModel.getValueAt(rowIndex, 2).toString());
	        int ToNo = Integer.parseInt(tblModel.getValueAt(rowIndex, 3).toString());
	        int FromNo = Integer.parseInt(tblModel.getValueAt(rowIndex, 4).toString());
	        if (EmpNo == 0 && ToNo == 0 & FromNo == 0)
	        {
	            return true;
	        } else {
	            JOptionPane.showMessageDialog(null,
	                    "You can not delete this department.\n  Have a some employees in this department.",
	                    "error",
	                    JOptionPane.ERROR_MESSAGE);
	            return false;
	        }
	    }

	    private void getEditData() {
	        int rowIndex = tblData.getSelectedRow();
	        tfEditDepartmentID.setText(tblModel.getValueAt(rowIndex, 0).toString());
	        tfEditDepartmentName.setText(tblModel.getValueAt(rowIndex, 1).toString());
	    }

	    private boolean validateEdit() {
	        String msg = "";
	        if (!ValidateFormTools.isFilledTextField(tfEditDepartmentName, true))
	        {
	            msg += "\n- Department name must not null.";
	        }
	        tfEditDepartmentName.setText(tfEditDepartmentName.getText().trim());
	        if (msg.compareTo("") != 0) {
	            JOptionPane.showMessageDialog(null,
	                    "Have error" + msg,
	                    "fixed error",
	                    JOptionPane.ERROR_MESSAGE);
	            return false;
	        } else {
	            return true;
	        }
	    }

	    private void loadTableData() {
	      //  try {
	            List<Department> departmentList = DepartmentDAO.selectAllDepartment();
	            tblModel = new DefaultTableModel();
	            tblModel.addColumn("STT");
	            tblModel.addColumn("Department name");
	            tblModel.addColumn("Number employees");
	             for (Department department : departmentList) {
	                Vector<String> row = new Vector<String>();
	                row.addElement(String.valueOf(department.getDepartmentId()));
	                row.addElement(department.getDepartmentName());
	                row.addElement(String.valueOf(department.getNumberOfEmployees()));
	                tblModel.addRow(row);
	            }
	            tblData.setModel(tblModel);
//	        } catch (ClassNotFoundException ex) {
//	            JOptionPane.showMessageDialog(null,
//	                    "",
//	                    "",
//	                    JOptionPane.ERROR_MESSAGE);
//	            ex.printStackTrace();
//	        } catch (SQLException ex) {
//	            JOptionPane.showMessageDialog(null,
//	                    "",
//	                    "",
//	                    JOptionPane.ERROR_MESSAGE);
//	            ex.printStackTrace();
//	        }

	    }


}
